(function(){
    require.config({
        paths: {
            Framework7:'framework7/framework7',
            Jquery:'jquery/jquery-1.11.2.min',
            Fullcalendar:'fullcalendar',
            Moment:'moment.min'

        },
        shim: {
            'Framework7':{exports: 'Framework7'}
        }
    });

    require(['Framework7','router','globalService','pageCtrl'], function (Framework7,router,GS,PC) {
        window.version = 1.0;
        window.requestTimeOut = 10000;
        //window.plugins.jPushPlugin.openNotificationInAndroidCallback = function(data){
        //
        //
        window.templates = {
            showOrderTemplate : Template7.compile($('#show-order-template').html()),
            showOrderInfoTemplate : Template7.compile($('#show-order-info-template').html()),
            showPersonInfoTemplate : Template7.compile($('#show-person-info-template').html()),
            showServiceTemplate : Template7.compile($('#show-service-template').html()),
            showServiceInfoTemplate : Template7.compile($('#show-service-info-template').html()),
            showContactTemplate : Template7.compile($('#show-contact-template').html()),
            showMessageContentTemplate : Template7.compile($('#show-message-content-template').html()),
            showMyPurseTemplate : Template7.compile($('#show-my-purse-template').html()),
            showMyMoneyListTemplate : Template7.compile($('#show-my-money-list-template').html()),
            showSheduleTableTemplate : Template7.compile($('#show-shedule-table-template').html())
        };
        window.appMain ={
           init:function(){
               //window.plugins.jPushPlugin.init();//推送初始化
               window.yunSpaceApp = new Framework7({
                   //cache:false,
                   //pushState:true,
                   swipePanel:'left',
                   pushStateSeparator:'#page/',
                   //swipePanelThreshold:20,
                   swipeBackPageAnimateShadow:false,//页面返回特效
                   swipeBackPageAnimateOpacity:false,//页面返回特效
                   swipeBackPageActiveArea:500,
                   template7Pages: true,
                   modalButtonOk:'确认',
                   swipePanelActiveArea:35,
                   modalButtonCancel:'取消',
                   //swipePanelNoFollow:'true',
                   template7Data: {
                       'page:order':{
                           //'name':'<a style="display: none">lihanbn</a>'
                       }
                   }
               })
               window.$$ = Dom7;
               window.mainView = yunSpaceApp.addView('#mainView', {
                   dynamicNavbar: true,
                   domCache: true,
                   //cache:false,s
                   pushState:true
               });
               window.messageView = yunSpaceApp.addView('#messageView', {
                   dynamicNavbar: true,
                   //cache:false,
                   pushState:true
               });
               window.serviceView = yunSpaceApp.addView('#serviceView', {
                   dynamicNavbar: true,
                   domCache: true,
                   //cache:false,
                   pushState:true
               });
               window.isGetMessage = false;


               $('#logOut').on('click', PC.logOut);


               $('#serviceView').on('show',function(){
                   if($('#serviceList li').size()<=0){
                       PC.serviceList();
                   }
               });
               
               $('#messageView').on('show', function () {
                   if($('#contactList li').size()<=0){
                       PC.getContacts();
                   }
               });

               $('#purseView').on('show', function () {
                   var html = $('#myPurse').html();
                   html = $.trim(html);
                   if(!html){
                       PC.pursePage();
                   }

               });

               $('#panelHomeLink').on('click', function () {
                   yunSpaceApp.showTab('#mainView');
               });
               $('#panelServiceLink').on('click', function () {
                   yunSpaceApp.showTab('#serviceView');
               });
               $('#panelMessageLink').on('click', function () {
                   yunSpaceApp.showTab('#messageView');
               });
               $('#panelPurseLink').on('click', function () {
                   yunSpaceApp.showTab('#purseView');
               });

               var ptrContent = $$('#purseView .pull-to-refresh-content');//添加钱包的下拉刷新
               ptrContent.on('refresh',function(){
                   pageCtrl.pursePage();
               });

               $('#mainView .no_content').on('click', PC.loginPage);

               document.addEventListener('deviceready', this.onDeviceReady, false);
               //document.addEventListener('touchmove', function(e) { e.preventDefault(); }, false);
               document.addEventListener("backbutton", this.onBackKeyDown, false);
               //document.addEventListener("jpush.openNotification", this.onOpenNotification, false);
               //document.addEventListener("jpush.receiveNotification", this.onReceiveNotification, false);
               router.init();
           },
            onDeviceReady: function() {
                //setTimeout(function(){
                    if (navigator.splashscreen) navigator.splashscreen.hide(); //隐藏介绍屏
                //},1500);
                //window.jpush_register_id = '';
            },
            onBackKeyDown:function(){
                if(!window.location.hash||window.location.hash=='#page/order.html'){
                    navigator.notification.confirm(
                        '确定要退出吗?',  // message
                        appMain.onConfirm,              // callback to invoke with index of button pressed
                        '提示',            // title
                        '退出,取消'          // buttonLabels
                    );
                }
                else{
                    window.history.go(-1);
                }
            },
            onConfirm:function(button){
                if(button==1){
                    navigator.app.exitApp();
                }
            },
            login:function(username2,password2){
                //window.plugins.jPushPlugin.getRegistrationID(function(data){//获取推送的用户ID
                //    window.jpush_register_id = data;
                //});
                var username = $.trim($('#login #username').val());
                var password = $.trim($('#login #password').val());
                username = username?username:username2;
                password = password?password:password2;
                if(!username||!password) {
                    yunSpaceApp.alert('用户名和密码不能为空！！','提示');
                    return false;
                }
                yunSpaceApp.showIndicator();
                var url =appMain.apiRoot+'vendor/login';
                var data = {
                    'username':username,
                    'password':password,
                    'device_platform':device.platform,
                    'device_uuid':device.uuid,
                    'device_version':device.version,
                    'device_model':device.model,
                    'app_version':window.version,
                    //'jpush_register_id':jpush_register_id
                };
                $$.ajax({
                    url:url,
                    type:'post',
                    dataType:'json',
                    timeout:requestTimeOut,
                    data:data,
                    success: function (data) {
                        if(data.status=='success'){
                            if(data.login_time) localStorage.setItem("login_time",data.login_time);
                            if(data.user_id) localStorage.setItem("user_id",data.user_id);
                            if(data.token) localStorage.setItem("user_token",data.token);
                            if(data.access_token) localStorage.setItem("access_token",data.access_token);
                            window.localUserId =data.user_id;
                            window.accessToken = data.access_token;
                            window.loginTime = data.login_time;
                            window.localToken = data.token;
                            $('.myName').text(data.username);
                            $('.myAccount span').text(data.fullname);
                            $('#user_info img').attr('src',data.avatar);
                            yunSpaceApp.params.swipePanel = 'left';

                            //订单页
                            if($("[data-page='order']").length > 0){
                                mainView.router.back('order.html');
                                PC.orderList();
                            }else{
                                mainView.router.loadPage('order.html');
                            }

                        }else{
                            yunSpaceApp.alert('登录失败！！','提示')
                            yunSpaceApp.hideIndicator();
                        }
                    },
                    error: function (XHR, TS, ET) {
                        appMain.networkError('',XHR,TS,ET);
                    }
                })
                return false
            },
            onOpenNotification:function(event){
                //try{
                //    var alertContent
                //    if(device.platform == "Android"){
                //        alertContent=window.plugins.jPushPlugin.openNotification.alert;
                //    }else{
                //        alertContent   = event.aps.alert;
                //    }
                //    alert("open Notificaiton:"+alertContent);
                //
                //}
                //catch(exception){
                //    alert("JPushPlugin:onOpenNotification"+exception);
                //}
            },

            onReceiveNotification : function () {
                try{
                    var message = window.plugins.jPushPlugin.receiveMessage.message;
                    //var extras = window.plugins.jPushPlugin.extras
                    alert(message);

                }
                catch(exception){
                    alert("JPushPlugin:onReceiveMessage-->"+exception);
                }
            },

            listImgOnerror : function () {
                var img=event.srcElement;
                img.src="images/vendor.jpg";
                img.onerror=null;
            },
            headImgOnerror : function () {
                var img=event.srcElement;
                img.src="images/head.jpg";
                img.onerror=null;
            },
            networkError : function(text,XMLHttpRequest, textStatus, errorThrown){
                if(!text){
                    text = '网络连接错误或超时！';
                }
                $('.top_tip').text(text).fadeIn();
                setTimeout(function(){
                    $('.top_tip').fadeOut();
                },2000);
                console.log(XMLHttpRequest.status);
                console.log(textStatus);
                console.log(errorThrown)
                yunSpaceApp.hideIndicator();
            },
            //apiRoot : 'http://www.yunspace.com.cn/app_api/'
            apiRoot : 'http://d15.yunspace.com.cn/app_api/'
            //apiRoot: 'http://localhost/pros/cool1/app_api/'
        }
        appMain.init();

    })

})();
